package com.zhangtai.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 鉴权资源服务器
 */
@Configuration
@EnableResourceServer// 标识为资源服务器，请求服务中的资源，就要带着token过来，找不到token或token是无效访问不了资源
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_ID = "mabach"; //resource_ids在认证服务器的数据库中

    @Autowired
    private TokenStore tokenStore;

    /**
     * 配置当前资源服务器的资源id，判断客户端有没有这个resource_ids，有则允许访问；
     * tokenStore:整合JwtToken
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).tokenStore(tokenStore);
        resources.tokenStore(tokenStore);
    }



    /***
     * 拦截配置
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.sessionManagement()//禁用session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //禁用session
                .and();
        http.authorizeRequests()//所有请求必须认证通过
                .antMatchers("/**").permitAll() //配置地址放行
//                TODO 测试时放行所有地址，生产的时候要去掉


                .anyRequest().access("#oauth2.hasScope('ehr')");   //其他地址需要有scope:"all"认证授权
        http.csrf().disable();

    }
}
